package com.lagou.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class UploadHelper {
    public static String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            throw new RuntimeException();
        }
        //D:\apache-tomcat-9.0.74\webapps\ssm_web
        //文件存储路径：D:\apache-tomcat-9.0.74\webapps\
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("/");
        String contextPath = servletContext.getContextPath();
        if (contextPath != "/") {
            contextPath = contextPath.replace("/", "");
        }
        int endIndex = realPath.lastIndexOf(contextPath);
        String finalPath = realPath.substring(0, endIndex);
        //获取原文件名
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().replace("-", "") + extName;
        String uploadPath = finalPath + "upload" + File.separator;
        File filePath = new File(uploadPath, fileName);
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdir();
        }
        file.transferTo(filePath);
        return fileName;
    }
}
